import 'package:BeeApp/MainPage/MainModelPage.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:BeeApp/ShopPage/UserRealNameModelPage.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

class UserRealNamePage extends StatefulWidget {
  UserRealNamePage({Key key}) : super(key: key);

  @override
  _UserRealNamePageState createState() => _UserRealNamePageState();
}

class _UserRealNamePageState extends State<UserRealNamePage> {
  UserRealNameModel realModel;
  final mobileText = TextEditingController();
  final nameText = TextEditingController();
  final codeText = TextEditingController();
  final otherText = TextEditingController();
  final otherMobileText = TextEditingController();
  List<Asset> images = List<Asset>();
  List<Asset> images01 = List<Asset>();
  List<Asset> images02 = List<Asset>();
  List<Asset> images03 = List<Asset>();

  String realStr = "";
  String realType = "提交审核";
  String imageStr01 = "";
  String imageStr02 = "";
  String imageStr03 = "";
  int chooseType;
  bool ischenge = true;

  @override
  void initState() {
    super.initState();
    uploadRealName();
  }

  void uploadRealName() {
    DioUtils.postHttp(
      context,
      "Usercommon/realname_info",
      parameters: {"token": getData("token")},
      onSuccess: (t) {
        print(t);
        MainModel model = MainModel.fromJson(t);
        if (model.code == 1 && model.data != null) {
          if (mounted) {
            setState(() {
              ischenge = false;
              realModel = UserRealNameModel.fromJson(t);
              realStr =
                  realModel.data.remark != null ? realModel.data.remark : "";
              if (realModel.data.auditStatus == 1) {
                realType = "审核中";
              } else {
                realType = "修改审核";
              }
              nameText.text = realModel.data.realname;
              codeText.text = realModel.data.idcard;
              mobileText.text = realModel.data.mobile;
              otherText.text = realModel.data.pressLinkMan;
              otherMobileText.text = realModel.data.linkManMobile;
              imageStr01 = realModel.data.idcardFrontImage;
              imageStr02 = realModel.data.idcardBackImage;
              imageStr03 = realModel.data.handIdcardFrontImage;
            });
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  Widget lineView() {
    return Container(
      height: 1,
      width: 900,
      color: Colors.grey[300],
    );
  }

  Text labelText(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Color(0xFF333333),
        fontSize: setFontSize(32),
        fontWeight: FontWeight.bold,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: Color(0xFFF5F5F5),
      backgroundColor: Colors.white,
      appBar: getAppBar(context, "实名认证"),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: ListView(
          children: <Widget>[
            Container(
              color: Color(0xFFF5F5F5),
              height: 8,
            ),
            Container(
              color: Colors.white,
              padding: EdgeInsets.only(
                left: setWidth(30),
                right: setWidth(30),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  realStr.length > 0
                      ? Container(
                          color: Colors.white,
                          child: Column(
                            children: [
                              SizedBox(height: 10),
                              Row(
                                children: [
                                  labelText("审核结果:"),
                                  SizedBox(width: 10),
                                  labelText(realStr),
                                ],
                              ),
                              SizedBox(height: 10),
                              lineView()
                            ],
                          ),
                        )
                      : Container(),
                  textView("姓    名：", "请输入姓名", nameText),
                  lineView(),
                  textView("身份证：", "请输入身份证", codeText),
                  lineView(),
                  textView(
                    "联系电话：",
                    "请输入电话",
                    mobileText,
                    keyType: TextInputType.phone,
                  ),
                  lineView(),
                  // textView("紧急联系人：", "请输入联系人姓名", otherText),
                  // lineView(),
                  // textView(
                  //   "紧急联系人电话：",
                  //   "请输入联系人电话",
                  //   otherMobileText,
                  //   keyType: TextInputType.phone,
                  // ),
                  // lineView(),
                  // SizedBox(height: setHeight(30)),
                  // labelText("请上传手持身份证照片"),
                  // SizedBox(height: setHeight(20)),
                  // Row(
                  //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  //   children: <Widget>[
                  //     chooseImageView("images/RealCodeImage01.png", "身份证正面", 1),
                  //     chooseImageView("images/RealCodeImage02.png", "身份证反面", 2),
                  //   ],
                  // ),
                  // SizedBox(height: setHeight(30)),
                  // chooseImageView("images/RealCodeImage01.png", "手持身份证正面", 3),
                  SizedBox(height: setHeight(60)),
                  btnView(),
                  SizedBox(height: 20),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget chooseImageView(String imageStr, String title, int index) {
    return Column(
      children: <Widget>[
        chooseView(imageStr, index),
        SizedBox(height: 8),
        Text(
          title,
          style: TextStyle(
            color: Color(0xFF666666),
            fontSize: setFontSize(28),
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    );
  }

  Widget chooseView(String imageStr, int index) {
    return InkWell(
      child: Container(
        alignment: Alignment.center,
        height: setHeight(210),
        width: (screenWidth - setWidth(80)) / 2,
        decoration: BoxDecoration(
          color: Colors.yellow,
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
          border: Border.all(
              color: index == 1 || index == 2 ? Colors.grey : Colors.white,
              width: 1),
          image: DecorationImage(
            image: AssetImage(imageStr),
            fit: BoxFit.cover,
          ),
        ),
        child: showimage(index),
      ),
      onTap: () async {
        print("object$index");
        chooseType = index;
        if (await Permission.camera.request().isGranted &&
            await Permission.photos.request().isGranted) {
          loadAssets();
          print('权限申请通过');
        } else {
          showToast('请前往设置，打开相机权限');
        }
      },
    );
  }

  Widget showimage(int index) {
    if (index == 1) {
      if (images01.length == 0 && realModel == null) {
        return Image.asset(
          "images/RealAddImage.png",
          width: setHeight(100),
          height: setHeight(100),
        );
      } else {
        if (images01.length > 0) {
          Asset asset = images01[0];
          return AssetThumb(
            asset: asset,
            width: 300,
            height: 300,
          );
        } else {
          return CachedNetworkImage(imageUrl: realModel.data.idcardFrontImage);
        }
      }
    } else if (index == 2) {
      if (images02.length == 0 && realModel == null) {
        return Image.asset(
          "images/RealAddImage.png",
          width: setHeight(100),
          height: setHeight(100),
        );
      } else {
        if (images02.length > 0) {
          Asset asset = images02[0];
          return AssetThumb(
            asset: asset,
            width: 300,
            height: 300,
          );
        } else {
          return CachedNetworkImage(imageUrl: realModel.data.idcardBackImage);
        }
      }
    } else if (index == 3) {
      if (images03.length == 0 && realModel == null) {
        return Image.asset(
          "images/RealAddImage.png",
          width: setHeight(100),
          height: setHeight(100),
        );
      } else {
        if (images03.length > 0) {
          Asset asset = images03[0];
          return AssetThumb(
            asset: asset,
            width: 300,
            height: 300,
          );
        } else {
          return CachedNetworkImage(
              imageUrl: realModel.data.handIdcardFrontImage);
        }
      }
    } else {
      return Image.asset(
        "images/RealAddImage.png",
        width: setHeight(100),
        height: setHeight(100),
      );
    }
  }

  // 获取相册图片
  Future<void> loadAssets() async {
    List<Asset> resultList = List<Asset>();
    String error = 'No Error Dectected';

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 1,
        enableCamera: true,
        selectedAssets: images,
        materialOptions: MaterialOptions(
          startInAllView: true,
          allViewTitle: "所有照片",
          actionBarColor: "#abcdef",
          textOnNothingSelected: "请选择图片",
          selectionLimitReachedText: "最多选择1张图片",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
      print("aaaaa" + error);
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    DioUtils.postImageHttp(
      context,
      "common/uploads",
      images: resultList,
      onSuccess: (t) {
        print(t);
        Map dic = Map.from(t);
        if (dic["code"] == 1) {
          setState(() {
            if (chooseType == 1) {
              images01 = resultList;
              imageStr01 = dic["data"]["url"][0];
            } else if (chooseType == 2) {
              images02 = resultList;
              imageStr02 = dic["data"]["url"][0];
            } else if (chooseType == 3) {
              images03 = resultList;
              imageStr03 = dic["data"]["url"][0];
            } else {}
          });
        }
      },
      onError: (error) {},
    );
  }

  Widget textView(
    String string,
    String hintStr,
    TextEditingController controller, {
    TextInputType keyType = TextInputType.text,
  }) {
    return Container(
      color: Colors.white,
      child: Row(
        children: [
          labelText(string),
          SizedBox(width: 10),
          Expanded(
              child: TextField(
            readOnly: !ischenge,
            controller: controller,
            textAlign: TextAlign.start,
            keyboardType: keyType,
            cursorColor: Colors.grey[400], //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: hintStr,
                hintStyle: TextStyle(
                    fontSize: setFontSize(30), color: Color(0xFFAEAEAE))),
            style: TextStyle(
              fontSize: setFontSize(30),
              color: Color(0xFF333333),
              fontWeight: FontWeight.bold,
            ),
          )),
        ],
      ),
    );
  }

  Widget btnView() {
    return Container(
      alignment: Alignment.center,
      child: InkWell(
        child: Container(
          width: setWidth(300),
          alignment: Alignment.center,
          padding: EdgeInsets.all(setHeight(20)),
          decoration: BoxDecoration(
            color: Color(0xFFFF8629),
            borderRadius: BorderRadius.all(Radius.circular(10)),
            border: Border.all(color: Colors.black, width: 2), //边框
          ),
          child: Text(
            realType,
            style: TextStyle(
              color: Color(0xFF222222),
              fontSize: setFontSize(34),
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        onTap: () {
          if (realModel.data.auditStatus == 1) {
            showToast("审核中，请等待");
            return;
          }
          if (ischenge) {
            uploadNews();
          } else {
            setState(() {
              ischenge = true;
            });
          }
        },
      ),
    );
  }

  void uploadNews() {
    removeFocus(context);
    if (nameText.text.length == 0) {
      showToast("请填写姓名");
      return;
    }
    if (codeText.text.length == 0) {
      showToast("请输入身份证");
      return;
    }
    if (!isPhone(mobileText.text)) {
      showToast("请输入正确的联系电话");
      return;
    }
    // if (otherText.text.length == 0) {
    //   showToast("请输入紧急联系人");
    //   return;
    // }
    // if (!isPhone(otherMobileText.text)) {
    //   showToast("请输入正确的紧急联系人电话");
    //   return;
    // }
    // if (imageStr01.length == 0) {
    //   showToast("请上传身份证正面照片");
    //   return;
    // }
    // if (imageStr02.length == 0) {
    //   showToast("请上传身份证反面照片");
    //   return;
    // }
    // if (imageStr03.length == 0) {
    //   showToast("请上传手持身份证正面照片");
    //   return;
    // }
    Map<String, dynamic> dic = Map();
    if (realModel != null) {
      dic["id"] = realModel.data.id.toString();
    }
    dic["token"] = getData("token");
    dic["realname"] = nameText.text;
    dic["idcard"] = codeText.text;
    dic["mobile"] = mobileText.text;
    // dic["press_link_man"] = otherText.text;
    // dic["link_man_mobile"] = otherMobileText.text;
    // dic["idcard_front_image"] = imageStr01;
    // dic["idcard_back_image"] = imageStr02;
    // dic["hand_idcard_front_image"] = imageStr03;
    showLoading(context);
    DioUtils.postHttp(
      context,
      "Usercenter/user_realname",
      parameters: dic,
      onSuccess: (t) {
        print(t);
        dismissLoading(context);
        // showToast(t["msg"]);
        showAlertDialog(context, t["msg"]);
      },
      onError: (error) {
        dismissLoading(context);
        print(error);
      },
    );
  }

  showAlertDialog(BuildContext context, String title) {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(title),
          // content: Text("确定要退出吗?"),
          // 设置成 圆角
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          actions: [
            FlatButton(
              child: Text(
                "确认",
                style: TextStyle(
                  color: Colors.orange,
                  fontSize: setFontSize(30),
                ),
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }
}
